Page({
  data: {
    nickname: ''
  },
  
  onLoad(options) {
    // 加载当前昵称
    const userInfo = wx.getStorageSync('userInfo') || {}
    this.setData({
      nickname: userInfo.nickname || ''
    })
  },
  
  onNicknameInput(e) {
    this.setData({
      nickname: e.detail.value
    })
  },
  
  save() {
    const { nickname } = this.data
    
    if (!nickname || !nickname.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }
    
    if (nickname.trim().length > 20) {
      wx.showToast({
        title: '昵称不能超过20个字符',
        icon: 'none'
      })
      return
    }
    
    // 更新本地存储
    const userInfo = wx.getStorageSync('userInfo') || {}
    userInfo.nickname = nickname.trim()
    wx.setStorageSync('userInfo', userInfo)
    
    // 更新全局数据
    const app = getApp()
    if (!app.globalData.userInfo) {
      app.globalData.userInfo = {}
    }
    app.globalData.userInfo.nickname = nickname.trim()
    
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500
    })
    
    setTimeout(() => {
      wx.navigateBack()
    }, 1500)
  }
})
